import CourtBooking from './CourtBooking';
import { getCampuses } from '@/lib/campusService';
import { getCourts } from '@/lib/courtsService';
import { getBookableTimeblocks, createBookOrder, getUserBookOrders, cancelBookOrder, getOrderForOutTradeNo, updateOrderPaymentByOutTradeNo } from "@/lib/courtBookingService";
import { jsapiPreOrder,generateJsApiPaySign,  } from '@/pay/payService';
import { getCurrentUser } from '@/lib/userService';

export default async function CourtBookingPage({ params }) {
  const campuses = await getCampuses({});
  const currentUser = await getCurrentUser();

  async function payOrder({openid,orderId,userName,courtName,timeDesc,price}) {
    'use server'
    //orderId need to be 32 length,but now it is 36 ,we should remove the last 4 characters
    console.log({openid,orderId,userName,courtName,timeDesc,price})

    //check if there is an order ready for payment
    let order = await getOrderForOutTradeNo(orderId);
    let prepay_id = order.memo;
    //FIXME: 不应该把prepay_id放在memo中，应用在用一个状态来表示 no_pay
    // check weather order.memo is null or undefined
    if (!order.memo || order.memo === "null" || order.memo === "undefined") {
      order = await jsapiPreOrder({
        openid: openid,
        description: `${openid} 预约${courtName}场地，${timeDesc}，${price}元`,
        totalFee: price * 100,
        tradeNo: orderId,
      });
      prepay_id = order.prepay_id;
    }
    console.log("prepay_id", prepay_id);
    const timestamp = Math.floor(Date.now() / 1000);
    const nonceStr = Math.random().toString(36).substring(2, 15);
    const paySign = generateJsApiPaySign({
      timestamp, // 自1970年1月1日 0点0分0秒以来的秒数
      nonceStr, // 随机字符串
      packageName: `prepay_id=${prepay_id}`,
    });
    const res = {
      appId: process.env.WECHAT_APP_ID,
      timeStamp: `${timestamp}`,
      nonceStr,
      package: `prepay_id=${prepay_id}`,
      signType: "RSA",
      paySign,
    }
    console.log("res", res);
    return res;
  }


  return (
    <CourtBooking
      lang={params.lang}
      campuses={campuses}
      getCourts={getCourts}
      getBookableTimeblocks={getBookableTimeblocks}
      createBookOrder={createBookOrder}
      getUserBookOrders={getUserBookOrders}
      cancelBookOrder={cancelBookOrder}
      payOrder={payOrder}
      currentUser={currentUser}
    />
  );
}